local zhilu = fk.CreateSkill {
  name = "lingling__zhilu",
}

Fk:loadTranslationTable{
  ["lingling__zhilu"] = "指鹿",
  [":lingling__zhilu"] = "出牌阶段限一次，你可以将一张牌当【无中生有】使用，然后你可以将一张牌当以此法获得的一张即时牌使用。",

  ["#lingling__zhilu"] = "指鹿：你可以将一张牌当【无中生有】使用",
  ["#lingling__zhilu-use"] = "指鹿：你可以将一张牌当其中一张即时牌使用",
}

zhilu:addEffect("viewas", {
  anim_type = "drawcard",
  mute_card = false,
  prompt = "#lingling__zhilu",
  handly_pile = true,
  card_filter = function(self, player, to_select, selected)
    return #selected == 0
  end,
  view_as = function(self, player, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("ex_nihilo")
    card.skillName = zhilu.name
    card:addSubcard(cards[1])
    return card
  end,
  after_use = function (self, player, use)
    local room = player.room
    if use.extra_data and use.extra_data.lingling__zhilu and
      not player.dead and not (#player:getHandlyIds() == 0 and player:isNude()) then
      room:askToUseVirtualCard(player, {
        name = use.extra_data.lingling__zhilu,
        skill_name = zhilu.name,
        prompt = "#lingling__zhilu-use",
        cancelable = true,
        extra_data = {
          bypass_times = true,
          extraUse = true,
        },
        card_filter = {
          n = 1,
        },
      })
    end
  end,
  enabled_at_play = function (self, player)
    return player:usedSkillTimes(zhilu.name, Player.HistoryPhase) == 0
  end,
})

zhilu:addEffect(fk.AfterCardsMove, {
  can_refresh = function (self, event, target, player, data)
    if player:hasSkill(zhilu.name, true) and player.phase == Player.Play then
      for _, move in ipairs(data) do
        if move.to == player and move.toArea == Card.PlayerHand and move.skillName == "ex_nihilo_skill" then
          local effect_event = player.room.logic:getCurrentEvent():findParent(GameEvent.CardEffect)
          if effect_event then
            local use = effect_event.data
            if table.contains(use.card.skillNames, zhilu.name) then
              event:setCostData(self, {extra_data = effect_event})
              return true
            end
          end
        end
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local names = {}
    for _, move in ipairs(data) do
      if move.to == player and move.toArea == Card.PlayerHand and move.skillName == "ex_nihilo_skill" then
        for _, info in ipairs(move.moveInfo) do
          local card = Fk:getCardById(info.cardId)
          if card.type == Card.TypeBasic or card:isCommonTrick() then
            table.insertIfNeed(names, card.name)
          end
        end
      end
    end
    if #names > 0 then
      local use_event = event:getCostData(self).extra_data:findParent(GameEvent.UseCard)
      if use_event then
        local use = use_event.data
        use.extra_data = use.extra_data or {}
        use.extra_data.lingling__zhilu = names
      end
    end
  end,
})

zhilu:addAI(nil, "vs_skill")

return zhilu
